#include "Action.h"
#include <unistd.h>
#include <stdio.h>
int Action::data[20]={0};

//a1= a1+a2
void arrayPlus(unsigned char *res,unsigned char *a1,unsigned char *a2)
{
    for(int i=0;i<20;i++)
    {
        res[i]=a1[i]|a2[i];
    }
}
//a1= a1*a2
int arrayMultiply(unsigned char *a1,unsigned char *a2)
{
    int sum=0;
    for(int i=0;i<20;i++)
    {
        sum+=a1[i]*a2[i];
    }
    return sum;
}

Action::Action(ACTION_FUN f,int d):delay(d),step(0)
{
    //ctor
    for(int i=0;i<20;i++)
    {
        used[i]=reject[i]=0;
    }
   fun.push_back(f);
}
double Action::play(double d)
{
    step+=d;
    if(step>=1)
        step=1;
    for(int i=0;i<fun.size();i++)
        fun[i](data,step);
    usleep(delay);
    return step;
}
Action Action::operator+(const Action& a)
{
    Action t=*this;
    bool wrong=false;
    arrayPlus(t.used,this->used,a.used);
    if(arrayMultiply(this->used,a.reject)>0)
        wrong=true;
    if(arrayMultiply(this->reject,a.used)>0)
        wrong=true;
    if(arrayMultiply(this->used,a.used)>0)
        wrong=true;
    if(wrong)
    {
        t.fun.clear();
        printf("error:ACTION REJECT!\n");
        return t;
    }
    for(int i=0;i<a.fun.size();i++)
        t.fun.push_back(a.fun[i]);
    return t;
}
void Action::run(double s)
{
    for(int i=0;i<fun.size();i++)
        fun[i](data,s);
    usleep(delay);
}
Action::~Action()
{
    //dtor
}
